<?php
  //name: updateGlobeampDB
  //utility: use to update date in the 'globemag' table
  //input: $db, database login parameters
  //output: nothing
  
  function updateGlobemagDB($db)
  {
      //collect the number of lines in the 'globe' table
      $req = "SELECT COUNT(*) AS nbrLine FROM globe";
      $reply = $db->query($req);
      $datas = $reply->fetch();
      $nbrLine = $datas['nbrLine'];
      
      
      //define the unit of the magnitude
      $MAGNITUDEUNIT = 0.1;
      for ($i = 1; $i <= $nbrLine; $i++) {
          //increase automatically at each loop
          //request preparation
          $req = $db->prepare('SELECT lat_cell, lon_cell FROM globe WHERE id=?');
          $req->execute(array($i));
          $lat_lon_globe = $req->fetch();
          $lat_tempo = $lat_lon_globe['lat_cell'];
          $lon_tempo = $lat_lon_globe['lon_cell'];
          
          //collect the magnitude of the line who match with the lat/lon couple
          $req = $db->prepare('SELECT mag FROM globemag WHERE lat_cell = ? AND lon_cell = ?');
          $req->execute(array($lat_tempo, $lon_tempo));
          $mag = $req->fetch();
          
          //if the magnitude of a line is superior to 1, the line's color will be black
          //to avoid this, we have to recompute $MAGNITUDEUNIT
          if ($mag['mag'] >= 1) {
              $MAGNITUDEUNIT = $MAGNITUDEUNIT / (1 + $MAGNITUDEUNIT);
              //we have to recompute all the datas
              $i = 1;
              //empty 'globemag' table
              $req = $db->prepare('DELETE FROM globemag');
              $req->execute(array());
              $req = $db->prepare('ALTER TABLE globemag AUTO_INCREMENT=0');
              $req->execute(array());
          } else {
              //if a line with the lat/lon couple already exist, we increment the magnitude value
              //else the line is created
              if ($mag != null) {
                  $req = $db->prepare('UPDATE globemag SET mag = :mag WHERE lat_cell = :lat_tempo AND lon_cell = :lon_tempo');
                  $req->execute(array('mag' => $mag['mag'] + $MAGNITUDEUNIT, 'lat_tempo' => $lat_tempo, 'lon_tempo' => $lon_tempo));
              } else {
                  $req = $db->prepare('INSERT INTO globemag(mag, lat_cell, lon_cell) VALUES(:mag, :lat_cell, :lon_cell)');
                  $req->execute(array('mag' => $MAGNITUDEUNIT, 'lat_cell' => $lat_tempo, 'lon_cell' => $lon_tempo));
              }
          }
      }
      
      
      echo "update of the globemag table finished" . '</br>';
  }
?>